<?php

namespace app\common\mqtt;

use addons\mycurrency\library\Common;
use app\common\library\device\cabinet\Analysis;
use app\common\library\device\cabinet\Logic;
use app\common\model\mycurrency\Device;
use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\Exceptions\MqttClientException;
use think\Db;
use think\Config;
use think\Log;
use function print_r;
use function time;
use function trace;
use function var_dump;

class MqttClientService
{
    private $mqtt;

    public function __construct()
    {
        $config = Config::get('mqtt');
        $this->mqtt = new MqttClient($config['server'], $config['port'], $config['client_id']);
        $connectionSettings = (new ConnectionSettings)
            ->setUsername($config['username'])
            ->setPassword($config['password'])
            ->setKeepAliveInterval(60);
        try {
            $this->mqtt->connect($connectionSettings, true);
        } catch (MqttClientException $e) {
            Log::error('连接失败: ' . $e->getMessage());
            throw $e;  // 抛出异常以便调用者知道发生了错误
        }
    }

    //消息订阅（接收设备上报的消息）
    public function subscribeToTopics()
    {
        $topicFilter = 'ZHZN/TAIQIU001';
        // 使用通配符订阅所有设备的主题
        try {
            $this->mqtt->subscribe($topicFilter, function (string $topic, string $message) {
                Log::info("Message received on topic {$topic}");
                $this->handleMessage('SleepRadar', $topic, $message);
            }, 0);

            $this->mqtt->loop(true);
        } catch (MqttClientException $e) {
            Log::error('MQTT subscription error: ' . $e->getMessage());
        }
    }

    //接收消息
    private function handleMessage($type, $topic, $message)
    {
        trace('========================接收到消息==============================');
        Log::info($message);
        $data = Analysis::analysis($message);
        trace('========================接收到消息-消息解析后==============================');
        Log::info([$data]);
        Logic::index($data);
    }

    private function extractDeviceId($topic, $type)
    {
        preg_match("/\/{$type}\/([^\/]+)\/sys\/property\/post/", $topic, $matches);
        return $matches[1];
    }

    public function __destruct()
    {
        if ($this->mqtt !== null) {
            $this->mqtt->disconnect();
            Log::info('Disconnected from MQTT broker.');
        }
    }


}